package com.sinan.core.connector;

import com.sinan.core.connector.components.PropertyContext;
import com.sinan.core.connector.components.PropertyDescriptor;
import com.sinan.core.connector.components.Validator;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * @author pengpei
 */
public class MySQLConnector extends JdbcConnector {

    public static final Set<String> MYSQL_DRIVERS = Set.of("com.mysql.jdbc.Driver", "com.mysql.cj.jdbc.Driver");

    public static final PropertyDescriptor DRIVER_CLASS = PropertyDescriptor.builder().name("driverClass").description("jdbc driver class")
            .required(true)
            .allowableValues(MYSQL_DRIVERS)
            .addValidator((subject, input) -> {
        if (StringUtils.isNotBlank(input)) {
            if (!MYSQL_DRIVERS.contains(input)) {
                return ValidationResult.builder().subject(subject).valid(false).input(input).explanation(String.format("driverClass is inValid, %s", input)).build();
            }
        }
        return Validator.VALID.validate(subject, input);
    }).build();

    public static final PropertyDescriptor URL = PropertyDescriptor.builder().name("url").description("jdbc url").required(true).addValidator((subject, input) -> {
        if (StringUtils.isNotBlank(input)) {
            if (!input.startsWith("jdbc:mysql//")) {
                return ValidationResult.builder().subject(subject).valid(false).input(input).explanation(String.format("\"%s\" [%s] is invalid, jdbc url must start with \"jdbc:mysql//\"", input, subject)).build();
            }
        }
        return Validator.VALID.validate(subject, input);
    }).build();

    public MySQLConnector(PropertyContext propertyContext) {
        super(propertyContext);
    }

    @Override
    protected String getDriverClass() {
        return getProperty(DRIVER_CLASS).getValue();
    }

    @Override
    protected String getUrl() {
        return getProperty(URL).getValue();
    }

    @Override
    protected File getDriverPath() {
        return Paths.get("../driver/mysql").resolve(getProductVersion()).toFile();
    }

    @Override
    public Collection<ValidationResult> customValidate() {
        return List.of();
    }
}
